﻿using UnityEngine;
using System.Collections;
using System;

namespace FrameWorkSong
{
    public class AssetBundleRes : Res
    {  
        string my_Path;
        public AssetBundle AssetBundle
        {
            get { return Asset as AssetBundle; }
            private set { Asset = value; }
        }
        public AssetBundleRes(string name, string path)
        {
            my_Path = path;
             Name = name;
            State = ResState.Waiting;
        }

        public override bool LoadAssetSync()
        {
            State = ResState.Loading;
            AssetBundle = AssetBundle.LoadFromFile(my_Path);
            State = ResState.Loaded;
            return AssetBundle;
        }

        public override void LoadAssetAsync()
        {
            State = ResState.Loading;
            var resRequest = AssetBundle.LoadFromFileAsync(my_Path);
            resRequest.completed += operation =>
            {
                AssetBundle = resRequest.assetBundle;
                State = ResState.Loaded;
            };
        }

        //IEnumerator IELoadAssetAsync(Action<Res> onLoaded, Action<float> progress)
        //{
        //    var resRequest = Resources.LoadAsync(my_Path);
        //    while (!resRequest.isDone)
        //    {
        //        progress(resRequest.progress);
        //        yield return new WaitForSeconds(0.01f);
        //    }
        //    if (resRequest.isDone)
        //    {
        //        Asset = resRequest.asset;
        //        onLoaded(this);
        //    }
        //}
     
        /// <summary>
        /// 销毁方法
        /// </summary>
        protected override void OnReleaseRes()
        {
            ReleaseAsset();
            ResMgr.Instance.ShareLoadedAssets.Remove(this);

        }

        public override void ReleaseAsset()
        {
            if (AssetBundle != null)
            {
                AssetBundle.Unload(true);
                AssetBundle = null;

            }
        }
    }
}
